package com.steven.im.ui.activity;

import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.steven.im.R;
import com.steven.im.areaselect.RxAreaSelectDialog;
import com.steven.im.base.BaseActivity;
import com.steven.im.entity.AddressEntity;
import com.steven.im.entity.BaseEntity;
import com.steven.im.net.MyCallback;
import com.steven.im.net.Task;
import com.steven.im.utils.GsonUtils;
import com.steven.im.utils.SaveParameterUtils;
import com.steven.im.utils.ScreenUtil;
import com.steven.im.utils.StringUtils;
import com.steven.im.utils.TitleBuilder;
import com.steven.im.utils.ToastUtil;
import com.steven.im.widget.SwitchButton;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Response;

/**
 * 添加收货地址
 */
public class AddaddrActivity extends BaseActivity {


    @BindView(R.id.tv_area)
    TextView tvArea;
    @BindView(R.id.et_receiver)
    EditText etReceiver;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.et_addr)
    EditText etAddr;
    @BindView(R.id.sb_default)
    SwitchButton sbDefault;

    String myRegionId = "";//省市区ID；
    int myStatus = 1;//默认地址（0，非默认，1，默认）
    String addressId = "";


    private RxAreaSelectDialog mDialog;//地址选择弹窗

    @Override
    public void setListen() {
    }

    @Override
    public void setTitleBarColor() {
        new TitleBuilder(this).setTitleText("添加收货地址")
                .setLeftIcoListening(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        finish();
                    }
                });
    }

    @Override
    public int intiLayout() {
        return R.layout.activity_addaddr;
    }

    @Override
    public void initView() {

        mDialog = new RxAreaSelectDialog(this);
        mDialog.setAnimation(R.style.Dialog_Up_Animation);
        mDialog.setResultCallBack(new RxAreaSelectDialog.OnSelectedResultCallBack() {
            @Override
            public void onResult(String regionId, String result, String province, String city, String area) {
                myRegionId = regionId;
                tvArea.setText(result);
            }
        });

        //默认开启地址
        sbDefault.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                if (isChecked) {
                    myStatus = 1;
                } else {
                    myStatus = 0;
                }
            }
        });
        sbDefault.setChecked(true);

        addressId = getIntent().getStringExtra("addressId");
    }

    @Override
    public void initData() {
        if (!TextUtils.isEmpty(addressId)) {
            modifyAddrInit();
        }
    }


    @OnClick({R.id.tv_area, R.id.tv_save})
    public void onViewClicked(View view) {
        if (ScreenUtil.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.tv_area:
                mDialog.show();
                break;
            case R.id.tv_save://保存
                if (checkInfo()) {
                    if (TextUtils.isEmpty(addressId)) {//添加地址
                        submitAddr();
                    } else {//修改地址
                        submitModify();
                    }
                }
                break;
        }
    }

    /**
     * 检测信息
     *
     * @return
     */
    private boolean checkInfo() {
        if (TextUtils.isEmpty(etReceiver.getText().toString().trim())) {
            ToastUtil.showShort(this, "请输入收货人");
            return false;
        }
        if (TextUtils.isEmpty(etPhone.getText().toString().trim())) {
            ToastUtil.showShort(this, "请输入手机号码");
            return false;
        } else if (!StringUtils.isPhone(this, etPhone.getText().toString().trim())) {
            return false;
        }
        if (TextUtils.isEmpty(myRegionId)) {
            ToastUtil.showShort(this, "请选择所在地区");
            return false;
        }
        if (TextUtils.isEmpty(etAddr.getText().toString().trim())) {
            ToastUtil.showShort(this, "请输入详细地址");
            return false;
        }
        return true;
    }

    /**
     * 添加地址
     */
    private void submitAddr() {

        String receiver = etReceiver.getText().toString().trim();
        String street = etAddr.getText().toString().trim();
        String mobile = etPhone.getText().toString().trim();
        String regionId = String.valueOf(myRegionId);
        String status = String.valueOf(myStatus);
        Log.i("submitAddr", "receiver:" + receiver + "  street=" + street);
        Task.getApiService().submitAddr(receiver, mobile, regionId, street, status)
                .enqueue(new MyCallback<BaseEntity>(this) {
                    @Override
                    protected void onSuccess(Response<BaseEntity> response) {
                        try {

                            SaveParameterUtils.saveToken(response.raw().header("token"));
                            if ("0".equals(response.body().getCode())) {
                                ToastUtil.showShort(AddaddrActivity.this, response.body().getMessage());
                                setResult(RESULT_OK);
                                finish();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    protected void onFailure(Throwable t) {

                    }
                });
    }

    /**
     * 编辑地址信息
     */
    private void modifyAddrInit() {

        Task.getApiService().modifyAddrInit(addressId).enqueue(new MyCallback<BaseEntity>(this) {
            @Override
            protected void onSuccess(Response<BaseEntity> response) {
                try {

                    if ("0".equals(response.body().getCode())) {
                        AddressEntity addressEntity = GsonUtils.parseJSON(
                                response.body().getResult().toString(), AddressEntity.class);
                        if (addressEntity != null) {
                            etReceiver.setText(addressEntity.getReceiver());
                            etPhone.setText(addressEntity.getMobile());
                            tvArea.setText(addressEntity.getRegionMergerName());
                            etAddr.setText(addressEntity.getStreet());
                            if ("1".equals(addressEntity.getStatus())) {
                                sbDefault.setChecked(true);
                                myStatus = 1;
                            } else {
                                sbDefault.setChecked(false);
                                myStatus = 0;
                            }

                            //设置参数
                            myRegionId = addressEntity.getRegionId();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected void onFailure(Throwable t) {

            }
        });
    }

    /**
     * 确认编辑地址
     */
    private void submitModify() {

        String receiver = etReceiver.getText().toString().trim();
        String street = etAddr.getText().toString().trim();
        String mobile = etPhone.getText().toString().trim();
        String regionId = String.valueOf(myRegionId);
        String status = String.valueOf(myStatus);
        Task.getApiService().submitModifyAddr(addressId, receiver, mobile, regionId, street, status).enqueue(new MyCallback<BaseEntity>(this) {
            @Override
            protected void onSuccess(Response<BaseEntity> response) {
                try {

                    ToastUtil.showShort(AddaddrActivity.this, response.body().getMessage());
                    if ("0".equals(response.body().getCode())) {
                        setResult(RESULT_OK);
                        finish();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected void onFailure(Throwable t) {

            }
        });
    }


}
